#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日志统计模块API路由
包含 Spring API 日志和 Minio 审计日志的查询接口
"""
import logging
from flask import Blueprint, request, jsonify
from app.services.log_service import LogService
from app.utils.logger import log_api_call

# 配置日志
logger = logging.getLogger(__name__)

logs_bp = Blueprint('logs', __name__, url_prefix='/api/logs')
log_service = LogService()


def success_response(data, message="操作成功"):
    """统一成功响应格式"""
    return {'success': True, 'data': data, 'message': message}


def error_response(message, code=500):
    """统一错误响应格式"""
    return {'success': False, 'message': message, 'error_code': code}


# ========== 前端日志接收接口 ==========

@logs_bp.route('', methods=['POST'])
def receive_frontend_log():
    """
    接收前端发送的日志
    
    Body Parameters:
        - level: 日志级别
        - levelName: 日志级别名称
        - logger: 日志器名称
        - message: 日志消息
        - data: 日志数据
        - timestamp: 时间戳
        - userAgent: 用户代理
        - url: 页面URL
        - userId: 用户ID
    """
    try:
        log_data = request.get_json()
        
        # 记录前端日志到后端日志系统
        level_name = log_data.get('levelName', 'INFO')
        message = log_data.get('message', '')
        logger_name = log_data.get('logger', 'Frontend')
        
        log_message = f"[Frontend-{logger_name}] {message}"
        
        if level_name == 'ERROR':
            logger.error(log_message, extra={'frontend_data': log_data})
        elif level_name == 'WARN':
            logger.warning(log_message, extra={'frontend_data': log_data})
        elif level_name == 'DEBUG':
            logger.debug(log_message, extra={'frontend_data': log_data})
        else:
            logger.info(log_message, extra={'frontend_data': log_data})
        
        return jsonify({'success': True, 'message': '日志已接收'}), 200
    
    except Exception as e:
        # 静默处理，不影响前端运行
        logger.error(f"接收前端日志失败: {e}", exc_info=True)
        return jsonify({'success': False, 'message': str(e)}), 200  # 返回200避免前端报错


# ========== Spring API 日志接口 ==========

@logs_bp.route('/api/services', methods=['GET'])
@log_api_call
def get_api_services():
    """
    获取所有可用的服务名称列表
    
    Query Parameters: 无
    """
    try:
        services = log_service.get_service_list()
        return jsonify(success_response({'services': services}, "获取服务列表成功"))
    
    except Exception as e:
        logger.error(f"获取服务列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取服务列表失败: {str(e)}")), 500


@logs_bp.route('/api/overview', methods=['GET'])
@log_api_call
def get_api_overview():
    """
    获取Spring API日志概览统计
    
    Query Parameters:
        - start_time: 开始时间（可选），格式：YYYY-MM-DD HH:MM:SS
        - end_time: 结束时间（可选），格式：YYYY-MM-DD HH:MM:SS
        - service_name: 服务名称（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        service_name = request.args.get('service_name')
        
        data = log_service.get_api_overview(start_time, end_time, service_name)
        return jsonify(success_response(data, "获取API概览统计成功"))
    
    except Exception as e:
        logger.error(f"获取API概览统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取API概览统计失败: {str(e)}")), 500


@logs_bp.route('/api/services/health', methods=['GET'])
@log_api_call
def get_service_health():
    """
    获取服务健康度排行
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_service_health(start_time, end_time)
        return jsonify(success_response(data, "获取服务健康度排行成功"))
    
    except Exception as e:
        logger.error(f"获取服务健康度排行失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取服务健康度排行失败: {str(e)}")), 500


@logs_bp.route('/api/trend', methods=['GET'])
@log_api_call
def get_api_trend():
    """
    获取请求趋势数据
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - service_names: 服务名称列表（可选），多个用逗号分隔
        - granularity: 时间粒度（hour/minute/day），默认hour
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        service_names_str = request.args.get('service_names')
        granularity = request.args.get('granularity', 'hour')
        
        service_names = None
        if service_names_str:
            service_names = [s.strip() for s in service_names_str.split(',')]
        
        data = log_service.get_api_trend(start_time, end_time, service_names, granularity)
        return jsonify(success_response(data, "获取请求趋势成功"))
    
    except Exception as e:
        logger.error(f"获取请求趋势失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取请求趋势失败: {str(e)}")), 500


@logs_bp.route('/api/services/apis', methods=['GET'])
@log_api_call
def get_service_apis():
    """
    获取各服务接口调用情况
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - service_name: 服务名称（可选）
        - top_n: 返回Top N接口，默认20
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        service_name = request.args.get('service_name')
        top_n = request.args.get('top_n', 20, type=int)
        
        data = log_service.get_service_apis(start_time, end_time, service_name, top_n)
        return jsonify(success_response(data, "获取服务接口调用情况成功"))
    
    except Exception as e:
        logger.error(f"获取服务接口调用情况失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取服务接口调用情况失败: {str(e)}")), 500


@logs_bp.route('/api/errors', methods=['GET'])
@log_api_call
def get_api_errors():
    """
    获取错误分析数据
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - service_name: 服务名称（可选）
        - top_n: 返回Top N错误，默认20
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        service_name = request.args.get('service_name')
        top_n = request.args.get('top_n', 20, type=int)
        
        data = log_service.get_api_errors(start_time, end_time, service_name, top_n)
        return jsonify(success_response(data, "获取错误分析成功"))
    
    except Exception as e:
        logger.error(f"获取错误分析失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取错误分析失败: {str(e)}")), 500


@logs_bp.route('/api/logs', methods=['GET'])
@log_api_call
def get_api_logs():
    """
    获取日志列表（分页）
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - service_name: 服务名称（可选）
        - api_path: 接口路径（可选）
        - http_method: HTTP方法（可选）
        - status_code: 状态码（可选）
        - success: 是否成功（可选，true/false）
        - environment: 环境标识（可选，dev/prod/test）
        - request_body: 请求体内容（可选，模糊匹配）
        - response_body: 响应体内容（可选，模糊匹配）
        - page: 页码，默认1
        - page_size: 每页大小，默认50
        - sort: 排序字段，默认log_timestamp
        - order: 排序方向(asc/desc)，默认desc
    """
    try:
        filters = {
            'start_time': request.args.get('start_time'),
            'end_time': request.args.get('end_time'),
            'service_name': request.args.get('service_name'),
            'api_path': request.args.get('api_path'),
            'http_method': request.args.get('http_method'),
            'status_code': request.args.get('status_code', type=int),
            'success': request.args.get('success', type=lambda x: x.lower() == 'true') if request.args.get('success') else None,
            'environment': request.args.get('environment'),
            'request_body': request.args.get('request_body'),
            'response_body': request.args.get('response_body')
        }
        
        # 移除None值
        filters = {k: v for k, v in filters.items() if v is not None}
        
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        sort_field = request.args.get('sort', 'log_timestamp')
        sort_order = request.args.get('order', 'desc')
        
        data = log_service.get_api_logs(filters, page, page_size, sort_field, sort_order)
        return jsonify(success_response(data, "获取日志列表成功"))
    
    except Exception as e:
        logger.error(f"获取日志列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取日志列表失败: {str(e)}")), 500


# ========== Minio 审计日志接口 ==========

@logs_bp.route('/minio/overview', methods=['GET'])
@log_api_call
def get_minio_overview():
    """
    获取Minio审计日志概览统计
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_minio_overview(start_time, end_time)
        return jsonify(success_response(data, "获取Minio概览统计成功"))
    
    except Exception as e:
        logger.error(f"获取Minio概览统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Minio概览统计失败: {str(e)}")), 500


@logs_bp.route('/minio/api-stats', methods=['GET'])
@log_api_call
def get_minio_api_stats():
    """
    获取Minio API类型分布统计
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_minio_api_stats(start_time, end_time)
        return jsonify(success_response(data, "获取Minio API统计成功"))
    
    except Exception as e:
        logger.error(f"获取Minio API统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Minio API统计失败: {str(e)}")), 500


@logs_bp.route('/minio/bucket-stats', methods=['GET'])
@log_api_call
def get_minio_bucket_stats():
    """
    获取Minio桶统计
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_minio_bucket_stats(start_time, end_time)
        return jsonify(success_response(data, "获取Minio桶统计成功"))
    
    except Exception as e:
        logger.error(f"获取Minio桶统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Minio桶统计失败: {str(e)}")), 500


@logs_bp.route('/minio/trend', methods=['GET'])
@log_api_call
def get_minio_trend():
    """
    获取Minio请求趋势
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - granularity: 时间粒度（hour/minute/day），默认hour
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        granularity = request.args.get('granularity', 'hour')
        
        data = log_service.get_minio_trend(start_time, end_time, granularity)
        return jsonify(success_response(data, "获取Minio趋势成功"))
    
    except Exception as e:
        logger.error(f"获取Minio趋势失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Minio趋势失败: {str(e)}")), 500


@logs_bp.route('/minio/logs', methods=['GET'])
@log_api_call
def get_minio_logs():
    """
    获取Minio审计日志列表
    
    Query Parameters:
        - start_time: 开始时间
        - end_time: 结束时间
        - api: API名称
        - bucket: 存储桶名称
        - object_key: 对象键
        - user_agent: User Agent
        - status_code: 状态码
        - page: 页码（默认1）
        - page_size: 每页大小（默认50）
        - sort: 排序字段，默认event_time
        - order: 排序方向(asc/desc)，默认desc
    
    Returns:
        JSON: 日志列表和分页信息
    """
    try:
        # 构建筛选条件
        filters = {}
        
        if request.args.get('start_time'):
            filters['start_time'] = request.args.get('start_time')
        if request.args.get('end_time'):
            filters['end_time'] = request.args.get('end_time')
        if request.args.get('api'):
            filters['api'] = request.args.get('api')
        if request.args.get('bucket'):
            filters['bucket'] = request.args.get('bucket')
        if request.args.get('object_key'):
            filters['object_key'] = request.args.get('object_key')
        if request.args.get('user_agent'):
            filters['user_agent'] = request.args.get('user_agent')
        if request.args.get('status_code'):
            filters['status_code'] = int(request.args.get('status_code'))
        
        # 分页参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 50))
        sort_field = request.args.get('sort', 'event_time')
        sort_order = request.args.get('order', 'desc')
        
        data = log_service.get_minio_logs(filters, page, page_size, sort_field, sort_order)
        return jsonify(success_response(data, "获取Minio日志列表成功"))
    
    except Exception as e:
        logger.error(f"获取Minio日志列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Minio日志列表失败: {str(e)}")), 500


# ========== Flink Job 日志接口 ==========

@logs_bp.route('/flink-job/jobs', methods=['GET'])
@log_api_call
def get_flink_job_list():
    """
    获取所有 Flink Job 名称列表
    
    Query Parameters: 无
    """
    try:
        jobs = log_service.get_flink_job_list()
        return jsonify(success_response({'jobs': jobs}, "获取Job列表成功"))
    
    except Exception as e:
        logger.error(f"获取Job列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Job列表失败: {str(e)}")), 500


@logs_bp.route('/flink-job/overview', methods=['GET'])
@log_api_call
def get_flink_job_overview():
    """
    获取 Flink Job 日志概览统计
    
    Query Parameters:
        - start_time: 开始时间（可选），格式：YYYY-MM-DD HH:MM:SS
        - end_time: 结束时间（可选），格式：YYYY-MM-DD HH:MM:SS
        - job_name: Job名称（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        job_name = request.args.get('job_name')
        
        data = log_service.get_flink_job_overview(start_time, end_time, job_name)
        return jsonify(success_response(data, "获取Flink Job概览统计成功"))
    
    except Exception as e:
        logger.error(f"获取Flink Job概览统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Flink Job概览统计失败: {str(e)}")), 500


@logs_bp.route('/flink-job/jobs/health', methods=['GET'])
@log_api_call
def get_flink_job_health():
    """
    获取 Flink Job 健康度排行
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_flink_job_health(start_time, end_time)
        return jsonify(success_response(data, "获取Job健康度排行成功"))
    
    except Exception as e:
        logger.error(f"获取Job健康度排行失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取Job健康度排行失败: {str(e)}")), 500


@logs_bp.route('/flink-job/trend', methods=['GET'])
@log_api_call
def get_flink_job_trend():
    """
    获取 Flink Job 日志趋势数据
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - job_names: Job名称列表（可选），多个用逗号分隔
        - granularity: 时间粒度（hour/minute/day），默认hour
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        job_names_str = request.args.get('job_names')
        granularity = request.args.get('granularity', 'hour')
        
        job_names = None
        if job_names_str:
            job_names = [s.strip() for s in job_names_str.split(',')]
        
        data = log_service.get_flink_job_trend(start_time, end_time, job_names, granularity)
        return jsonify(success_response(data, "获取日志趋势成功"))
    
    except Exception as e:
        logger.error(f"获取日志趋势失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取日志趋势失败: {str(e)}")), 500


@logs_bp.route('/flink-job/errors', methods=['GET'])
@log_api_call
def get_flink_job_errors():
    """
    获取 Flink Job 错误分析数据
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - job_name: Job名称（可选）
        - log_level: 日志级别（可选，ERROR/WARN/EXCEPTION），默认ERROR
        - top_n: 返回Top N错误，默认20
    """
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        job_name = request.args.get('job_name')
        log_level = request.args.get('log_level', 'ERROR')
        top_n = request.args.get('top_n', 20, type=int)
        
        data = log_service.get_flink_job_errors(start_time, end_time, job_name, log_level, top_n)
        return jsonify(success_response(data, "获取错误分析成功"))
    
    except Exception as e:
        logger.error(f"获取错误分析失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取错误分析失败: {str(e)}")), 500


@logs_bp.route('/flink-job/logs', methods=['GET'])
@log_api_call
def get_flink_job_logs():
    """
    获取 Flink Job 日志列表（分页）
    
    Query Parameters:
        - start_time: 开始时间（可选）
        - end_time: 结束时间（可选）
        - job_name: Job名称（可选）
        - job_id: Job ID（可选）
        - env: 环境（可选）
        - log_level: 日志级别（可选）
        - logger_name: Logger名称（可选）
        - class_name: 类名（可选）
        - message: 消息内容（可选）
        - page: 页码，默认1
        - page_size: 每页大小，默认50
        - sort: 排序字段，默认log_timestamp
        - order: 排序方向(asc/desc)，默认desc
    """
    try:
        filters = {
            'start_time': request.args.get('start_time'),
            'end_time': request.args.get('end_time'),
            'job_name': request.args.get('job_name'),
            'job_id': request.args.get('job_id'),
            'env': request.args.get('env'),
            'log_level': request.args.get('log_level'),
            'logger_name': request.args.get('logger_name'),
            'class_name': request.args.get('class_name'),
            'message': request.args.get('message')
        }
        
        # 移除None值
        filters = {k: v for k, v in filters.items() if v is not None}
        
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        sort_field = request.args.get('sort', 'log_timestamp')
        sort_order = request.args.get('order', 'desc')
        
        data = log_service.get_flink_job_logs(filters, page, page_size, sort_field, sort_order)
        return jsonify(success_response(data, "获取日志列表成功"))
    
    except Exception as e:
        logger.error(f"获取日志列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取日志列表失败: {str(e)}")), 500


# ========== StarRocks 错误日志接口 ==========

@logs_bp.route('/starrocks-error/clusters', methods=['GET'])
@log_api_call
def get_starrocks_error_clusters():
    """获取 StarRocks 错误日志的集群列表"""
    try:
        data = log_service.get_starrocks_error_clusters()
        return jsonify(success_response(data, "获取集群列表成功"))
    except Exception as e:
        logger.error(f"获取集群列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取集群列表失败: {str(e)}")), 500


@logs_bp.route('/starrocks-error/overview', methods=['GET'])
@log_api_call
def get_starrocks_error_overview():
    """获取 StarRocks 错误日志概览统计"""
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        cluster = request.args.get('cluster')

        data = log_service.get_starrocks_error_overview(start_time, end_time, cluster)
        return jsonify(success_response(data, "获取概览统计成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 错误日志概览统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取 StarRocks 错误日志概览统计失败: {str(e)}")), 500


@logs_bp.route('/starrocks-error/trend', methods=['GET'])
@log_api_call
def get_starrocks_error_trend():
    """获取 StarRocks 错误日志趋势"""
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        cluster = request.args.get('cluster')
        granularity = request.args.get('granularity', 'hour')

        data = log_service.get_starrocks_error_trend(start_time, end_time, cluster, granularity)
        return jsonify(success_response(data, "获取趋势数据成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 错误日志趋势失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取 StarRocks 错误日志趋势失败: {str(e)}")), 500


@logs_bp.route('/starrocks-error/fingerprints', methods=['GET'])
@log_api_call
def get_starrocks_error_fingerprints():
    """获取 StarRocks 错误日志指纹聚合"""
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        cluster = request.args.get('cluster')
        level = request.args.get('details_level')
        top_n = request.args.get('top_n', 20, type=int)

        data = log_service.get_starrocks_error_fingerprints(start_time, end_time, cluster, level, top_n)
        return jsonify(success_response(data, "获取错误指纹成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 错误指纹失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取 StarRocks 错误指纹失败: {str(e)}")), 500


@logs_bp.route('/starrocks-error/logs', methods=['GET'])
@log_api_call
def get_starrocks_error_logs():
    """获取 StarRocks 错误日志列表"""
    try:
        logger.info("=" * 80)
        logger.info("调用 StarRocks 错误日志列表接口")
        logger.info(f"请求参数: {dict(request.args)}")
        logger.info("=" * 80)
        
        filters = {
            'start_time': request.args.get('start_time'),
            'end_time': request.args.get('end_time'),
            'cluster': request.args.get('cluster'),
            'component': request.args.get('component'),
            'details_level': request.args.get('details_level'),
            'node_type': request.args.get('node_type'),
            'node_ip': request.args.get('node_ip'),
            'message': request.args.get('message'),
            'fingerprint': request.args.get('fingerprint')
        }

        # 移除空值
        filters = {k: v for k, v in filters.items() if v is not None and v != ''}

        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        sort_field = request.args.get('sort', 'details_timestamp')
        sort_order = request.args.get('order', 'desc')

        data = log_service.get_starrocks_error_logs(filters, page, page_size, sort_field, sort_order)
        logger.info(f"返回数据: total={data.get('total')}, logs_count={len(data.get('logs', []))}")
        return jsonify(success_response(data, "获取日志列表成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 错误日志列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取 StarRocks 错误日志列表失败: {str(e)}")), 500


# ========== StarRocks 查询日志接口 ==========

@logs_bp.route('/starrocks-query/logs', methods=['GET'])
@log_api_call
def get_starrocks_query_logs():
    """获取 StarRocks 查询日志列表"""
    try:
        logger.info("=" * 80)
        logger.info("调用 StarRocks 查询日志列表接口")
        logger.info(f"请求参数: {dict(request.args)}")
        logger.info("=" * 80)
        
        filters = {
            'start_time': request.args.get('start_time'),
            'end_time': request.args.get('end_time'),
            'cluster': request.args.get('cluster'),
            'query_user': request.args.get('query_user'),
            'query_database': request.args.get('query_database'),
            'query_state': request.args.get('query_state'),
            'query_stmt': request.args.get('query_stmt')
        }
        
        # 慢查询筛选
        is_slow_query_str = request.args.get('is_slow_query')
        if is_slow_query_str:
            filters['is_slow_query'] = is_slow_query_str
        
        # 查询类型筛选
        is_query_str = request.args.get('is_query')
        if is_query_str:
            filters['is_query'] = is_query_str
        
        # 移除空值
        filters = {k: v for k, v in filters.items() if v is not None and v != ''}
        
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        sort_field = request.args.get('sort', 'query_timestamp')
        sort_order = request.args.get('order', 'desc')
        
        data = log_service.get_starrocks_query_logs(filters, page, page_size, sort_field, sort_order)
        logger.info(f"返回数据: total={data.get('total')}, logs_count={len(data.get('logs', []))}")
        return jsonify(success_response(data, "获取查询日志列表成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询日志列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取 StarRocks 查询日志列表失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/users', methods=['GET'])
@log_api_call
def get_starrocks_query_users():
    """获取 StarRocks 查询日志用户列表"""
    try:
        users = log_service.get_starrocks_query_users()
        return jsonify(success_response({'users': users}, "获取用户列表成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询用户列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取用户列表失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/databases', methods=['GET'])
@log_api_call
def get_starrocks_query_databases():
    """获取 StarRocks 查询日志数据库列表"""
    try:
        databases = log_service.get_starrocks_query_databases()
        return jsonify(success_response({'databases': databases}, "获取数据库列表成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 数据库列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取数据库列表失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/clusters', methods=['GET'])
@log_api_call
def get_starrocks_query_clusters():
    """获取 StarRocks 查询日志集群列表"""
    try:
        clusters = log_service.get_starrocks_query_clusters()
        return jsonify(success_response({'clusters': clusters}, "获取集群列表成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询集群列表失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取集群列表失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/overview', methods=['GET'])
@log_api_call
def get_starrocks_query_overview():
    """获取 StarRocks 查询日志概览统计"""
    try:
        cluster = request.args.get('cluster')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_starrocks_query_overview(cluster, start_time, end_time)
        return jsonify(success_response(data, "获取查询概览统计成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询概览统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取查询概览统计失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/trend', methods=['GET'])
@log_api_call
def get_starrocks_query_trend():
    """获取 StarRocks 查询日志趋势"""
    try:
        cluster = request.args.get('cluster')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        granularity = request.args.get('granularity', 'hour')
        
        data = log_service.get_starrocks_query_trend(cluster, start_time, end_time, granularity)
        return jsonify(success_response(data, "获取查询趋势成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询趋势失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取查询趋势失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/user-stats', methods=['GET'])
@log_api_call
def get_starrocks_query_user_stats():
    """获取 StarRocks 查询日志用户维度统计"""
    try:
        cluster = request.args.get('cluster')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        top_n = request.args.get('top_n', 20, type=int)
        
        data = log_service.get_starrocks_query_user_stats(cluster, start_time, end_time, top_n)
        return jsonify(success_response(data, "获取用户统计成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询用户统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取用户统计失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/database-stats', methods=['GET'])
@log_api_call
def get_starrocks_query_database_stats():
    """获取 StarRocks 查询日志数据库维度统计"""
    try:
        cluster = request.args.get('cluster')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        top_n = request.args.get('top_n', 20, type=int)
        
        data = log_service.get_starrocks_query_database_stats(cluster, start_time, end_time, top_n)
        return jsonify(success_response(data, "获取数据库统计成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询数据库统计失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取数据库统计失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/cluster-distribution', methods=['GET'])
@log_api_call
def get_starrocks_query_cluster_distribution():
    """获取 StarRocks 查询日志集群分布"""
    try:
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        
        data = log_service.get_starrocks_query_cluster_distribution(start_time, end_time)
        return jsonify(success_response(data, "获取集群分布成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 查询集群分布失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取集群分布失败: {str(e)}")), 500


@logs_bp.route('/starrocks-query/top-queries', methods=['GET'])
@log_api_call
def get_starrocks_query_top_queries():
    """获取 StarRocks 热门SQL分析"""
    try:
        cluster = request.args.get('cluster')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        top_n = request.args.get('top_n', 20, type=int)
        order_by = request.args.get('order_by', 'count')
        
        data = log_service.get_starrocks_query_top_queries(cluster, start_time, end_time, top_n, order_by)
        return jsonify(success_response(data, "获取热门SQL成功"))
    except Exception as e:
        logger.error(f"获取 StarRocks 热门SQL失败: {e}", exc_info=True)
        return jsonify(error_response(f"获取热门SQL失败: {str(e)}")), 500
